import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25397
 * Date: 2022-03-02
 * Time: 22:21
 */

public enum TestEnum2 {
    RED("red",1),BLACK("black",2),GREEN("green",9),WHITE("white",3);
    public String color;
    public int ordinal;

    TestEnum2(String color,int ordinal){
        //因为我们是默认继承Enum类的，所以这里写构造方法，要先帮父类构造

        this.color=color;
        this.ordinal=ordinal;
    }

    public static void reflectPrivateConstructor() throws ClassNotFoundException {
        try{
            Class<?> classEnum=Class.forName("TestEnum1");

            Constructor<?> declaredConstructor =classEnum.getDeclaredConstructor(String.class,int.class);
            declaredConstructor.setAccessible(true);

            Object object=declaredConstructor.newInstance("绿色",666,"hhh",520);
            TestEnum2 testEnum2=(TestEnum2) object;
            System.out.println("获取枚举的私有构造函数:"+testEnum2);
        }catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        reflectPrivateConstructor();//会报警告，枚举非常安全，你通过反射无法获得枚举对象
    }
}
